package com.cloud.utils;

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JSONUtils {

    private static Logger logger = LoggerFactory.getLogger(JSONUtils.class);

    public static String toJson(Object object) {
        String json = null;
        if (ObjectUtils.isEmpty(object)) {
            return null;
        } else {
            try {
                json = JSONUtil.toJsonStr(object);
            } catch (Exception e) {
                logger.error("转换为JSON字符串失败:", e);
            }
        }
        return json;
    }

    public static <T> T toObject(String json, Class<T> tClass) {
        T object = null;
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            try {
                object = JSONUtil.toBean(json, tClass);
            } catch (Exception e) {
                logger.error("从JSON字符串转换失败:", e);
            }
        }
        return object;
    }

}
